package com.flx.noodle.websocket.controller;

import com.flx.noodle.websocket.entity.SSOUser;
import com.flx.noodle.websocket.searcher.UserSearcher;
import com.flx.noodle.websocket.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * Created by fenglixiong on 2017/10/2.
 */
@Controller
@RequestMapping("/user")
public class UserController{

    @Autowired
    private UserService userService;

    @RequestMapping("/userList.htm")
    public String userList(@RequestParam(value = "page",required = false,defaultValue = "1")Integer page,
                           @RequestParam(value = "pageSize",required = false,defaultValue = "10")Integer pageSize,
                           @RequestParam(value = "userId",required = false)Integer userId,
                           @RequestParam(value = "userName",required = false)String userName,
                           HttpServletRequest request, ModelMap model){
        UserSearcher searcher = new UserSearcher();
        searcher.setPage(page);
        searcher.setPageSize(pageSize);
        searcher.setUserId(userId);
        searcher.setUserName(userName);
        List<SSOUser> userList = userService.findUserList(searcher);
        model.addAttribute("userList",userList);
        model.addAttribute("ps",searcher);
        return "user/user_list";
    }

    @RequestMapping("/userAdd.htm")
    public String addUser(){
        return "user/user_add";
    }

    @RequestMapping("/userEdit.htm")
    public String editUser(@RequestParam(value = "userId")Integer userId,ModelMap model){
        SSOUser ssoUser = userService.getUserById(userId);
        model.addAttribute("user",ssoUser);
        return "user/user_add";
    }

    @RequestMapping("/saveOrUpdate.htm")
    public String saveOrUpdate(@ModelAttribute SSOUser ssoUser){
        userService.saveOrUpdateUser(ssoUser);
        return "redirect:/user/userList.htm";
    }

    @RequestMapping("/userDelete.htm")
    public String deleteUser(@RequestParam(value = "userId")Integer userId){
        userService.deleteUser(userId);
        return "redirect:/user/userList.htm";
    }

    @RequestMapping("/getUserBySessionId.json")
    public @ResponseBody
    SSOUser getUserBySessionId(HttpServletResponse response,
                               @RequestParam(value = "sessionId")String sessionId) throws IOException {
        SSOUser user = userService.getUserBySessionId(sessionId);
        return user;
    }

}
